const fs = require('fs');
const path = require('path');
const glob = require('glob');

// 查找所有的 .scss 和包含 <style lang="scss"> 的 .vue 文件
const findFiles = () => {
  return new Promise((resolve, reject) => {
    glob('src/**/*.{scss,vue}', (err, files) => {
      if (err) {
        reject(err);
      } else {
        resolve(files);
      }
    });
  });
};

// 更新 @import 为 @use 和 @forward
const updateImports = (content) => {
  // 替换 @import 为 @use
  return content.replace(/@import\s+['"](.+)['"]\s*;/g, (match, importPath) => {
    // 如果是导入 index.scss 或者其他样式文件，使用 @use
    return `@use '${importPath}' as *;`;
  });
};

// 更新全局内置函数
const updateGlobalFunctions = (content) => {
  return content
    .replace(/\bmap-merge\b/g, 'map.merge')
    .replace(/\bmap-get\b/g, 'map.get')
    .replace(/\bstr-slice\b/g, 'string.slice')
    .replace(/\bstr_index\b/g, 'string.index')
    .replace(/\bstr-index\b/g, 'string.index')
    .replace(/\binspect\b(?!\s*\.\s*)/g, 'meta.inspect');
};

// 处理 !global 变量声明
const updateGlobalVariables = (content) => {
  // 查找所有使用 !global 的变量
  const globalVars = new Set();
  const regex = /\$([a-zA-Z0-9_-]+):.+!global/g;
  let match;
  
  while ((match = regex.exec(content)) !== null) {
    globalVars.add(match[1]);
  }
  
  // 在文件顶部添加变量声明
  let newContent = content;
  if (globalVars.size > 0) {
    const declarations = Array.from(globalVars).map(varName => `$${varName}: null;`).join('\n');
    newContent = declarations + '\n\n' + newContent;
  }
  
  return newContent;
};

// 处理 Vue 文件中的 <style> 块
const processVueFile = async (filePath) => {
  const content = fs.readFileSync(filePath, 'utf8');
  const styleRegex = /<style.*?lang=["']scss["'].*?>([\s\S]*?)<\/style>/g;
  
  let newContent = content;
  let match;
  
  while ((match = styleRegex.exec(content)) !== null) {
    const styleContent = match[1];
    let updatedStyle = updateImports(styleContent);
    updatedStyle = updateGlobalFunctions(updatedStyle);
    updatedStyle = updateGlobalVariables(updatedStyle);
    
    newContent = newContent.replace(styleContent, updatedStyle);
  }
  
  if (newContent !== content) {
    fs.writeFileSync(filePath, newContent, 'utf8');
    console.log(`Updated Vue file: ${filePath}`);
  }
};

// 处理 SCSS 文件
const processScssFile = async (filePath) => {
  const content = fs.readFileSync(filePath, 'utf8');
  
  let newContent = updateImports(content);
  newContent = updateGlobalFunctions(newContent);
  newContent = updateGlobalVariables(newContent);
  
  if (newContent !== content) {
    fs.writeFileSync(filePath, newContent, 'utf8');
    console.log(`Updated SCSS file: ${filePath}`);
  }
};

// 主函数
const main = async () => {
  try {
    const files = await findFiles();
    
    for (const file of files) {
      if (file.endsWith('.vue')) {
        await processVueFile(file);
      } else if (file.endsWith('.scss')) {
        await processScssFile(file);
      }
    }
    
    console.log('Migration completed successfully!');
  } catch (error) {
    console.error('Error during migration:', error);
  }
};

main();